package com.zwp.base.base

import androidx.lifecycle.viewModelScope
import androidx.paging.*
import androidx.recyclerview.widget.DiffUtil
import com.zwp.base.paging.BasePagingSource
import com.zwp.base.paging.BindingRecyclerViewAdapter
import com.zwp.base.state.EmptyState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.tatarka.bindingcollectionadapter2.ItemBinding


abstract class BaseListViewModel<T : Any> : BaseViewModel() {

    val adapter by lazy {
        BindingRecyclerViewAdapter(diffCallback).apply {
            addLoadStateListener {
                when (it.refresh) {
                    is LoadState.Loading -> {
                        uc.showDialogEvent.postValue(null)
                        stateModel.emptyState = EmptyState.PROGRESS
                    }
                    is LoadState.Error -> {
                        uc.dismissDialogEvent.call()
                        stateModel.emptyState = EmptyState.NET_ERROR
                    }
                    is LoadState.NotLoading -> {
                        uc.dismissDialogEvent.call()
                        stateModel.emptyState = EmptyState.NORMAL
                    }
                }
            }
        }
    }

    open val diffCallback: DiffUtil.ItemCallback<T> = object :DiffUtil.ItemCallback<T>() {
        override fun areItemsTheSame(oldItem: T, newItem: T): Boolean = false

        override fun areContentsTheSame(oldItem: T, newItem: T): Boolean = false

    }

    suspend fun submitData(data: PagingData<T>) {
        adapter.submitData(data)
    }

    abstract val itemBinding : ItemBinding<T>

    protected fun <T : Any> paging(pageSize: Int = 10, loadData: suspend (Int) -> List<T>) =
        Pager(
            config = PagingConfig(pageSize),
            pagingSourceFactory = {
                BasePagingSource {
                    delay(3000)
                    loadData.invoke(it)
                }
            }
        ).flow.cachedIn(viewModelScope)
}